package org.easy.alisms;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class AlibabaSmsTemplate {

    private String appId;
    private String appKey;

    public AlibabaSmsTemplate(String appId, String appKey) {
        this.appId = appId;
        this.appKey = appKey;
    }

    /**
     * @param phone
     * @param params       模板里面的替换参数
     * @param templateCode 模板CODE  SMS_305017069
     * @param smsSign
     * @return
     */
    public Boolean sendSmsCode(String phone, Map<String, Object> params, String templateCode, String smsSign) {
        return sendSmsCode(phone, params, "", templateCode, smsSign);
    }

    public Boolean sendSmsCode(String phone, Map<String, Object> params, String areaCode, String templateCode, String smsSign) {

        try {
            //初始化
            Client client = AliyunSmsUtil.createClient(appId, appKey);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(smsSign)
                    .setTemplateCode(templateCode)
                    .setPhoneNumbers(areaCode + phone)
                    .setTemplateParam(JSON.toJSONString(params));

            SendSmsResponse response = client.sendSms(sendSmsRequest);

            String codeStr = response.body.code;
            if (!com.aliyun.teautil.Common.equalString(codeStr, "OK")) {
                log.error("sendSmsCode send fail {}  {} ", response.body.message, phone);
                return false;
            }
            log.info("sendSmsCode send success {}  {}", phone, templateCode);
            return true;
        } catch (Exception e) {
            log.error("sendSmsCode send fail {} {}  {}", phone, templateCode, e.getMessage());
            throw new RuntimeException(e);
        }

    }


}
